<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-row>
      <el-col :span="22">
          <el-form :model="searchForm" :inline="true" label-width="70px">
            <el-form-item label="提箱单号" style="width:260px">
              <el-input v-model="searchForm.packingNo" clearable placeholder="请输入提箱单号"></el-input>
            </el-form-item>
            <el-form-item label="业务编号" style="width:260px">
              <el-input v-model.trim="searchForm.businessNo" clearable placeholder="请输入业务编号"> </el-input>
            </el-form-item>
            <el-form-item label="堆场名称" style="width:260px">
              <el-input v-model="searchForm.yardName" clearable placeholder="请输入堆场名称"></el-input>
            </el-form-item>
            <el-form-item label="箱况" style="width:260px">
              <el-select v-model="searchForm.boxCase" clearable style="width:100%" placeholder="选择箱况">
                <el-option v-for="item in param.boxCaseOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="箱东公司" style="width:260px">
              <el-input v-model="searchForm.companyName" clearable placeholder="请输入箱东公司名称"></el-input>
            </el-form-item>
            <!-- <el-form-item v-if="param.tagName != 'returnBox'" style="width:250px">
              <div>提箱单类型</div>
              <el-select v-model="searchForm.orderType" clearable style="width:100%" placeholder="选择箱况">
                <el-option v-for="item in param.orderTypes" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="订单号" style="width:260px">
              <el-input v-model="searchForm.orderNo" clearable placeholder="请输入订单号"></el-input>
            </el-form-item>
          </el-form>
      </el-col>
      <el-col :span="2">
        <el-row justify="center">
            <el-col :span="24" class="text-center"><el-button @click="handleReSet" :icon="Refresh">重置</el-button></el-col>
            <el-col :span="24" class="text-center marginTop10"><el-button @click="getTableData" :icon="Search" type="primary" class="marginTop15">查询</el-button></el-col>
        </el-row>
      </el-col>
    </el-row>

    <cz-tages :typeList="typeList" @handleTypeChange="handleTypeChange"></cz-tages>
    
    <Table v-bind="table" style="width: 100%;" @pageChange="onTablePageChange"
      @downloadFile="downloadFile" @showPackingRecord="showPackingRecord" @goAddPackingRecord="goAddPackingRecord"
      @endPacking="endPacking" @handleShowContract="handleShowContract" @showInfo="showInfo">
    </Table>
    
    <!-- 添加提箱记录 -->
    <el-drawer v-model="param.drawerPackingRecord" :destroy-on-close="'true'" @close="resetForm" :with-header="false" size="800px">
      <span class="_before">添加提箱记录</span>
      <el-form :model="param" ref="packingRecordFormRef" :rules="packingRecordFormRules" label-width="100px"
        style="margin-top: 20px;">
        <el-form-item :label-width="'35px'">
          <div style=" color:#606266;font-weight: 600" class="_asterisk">选择订单</div>
          <el-table  ref="singleTableRef" :data="param.orderList" :row-key="orderId" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="30"></el-table-column>
            <el-table-column prop="orderNo" width="200" label="订单号" align="center"></el-table-column>
            <el-table-column prop="orderTime" width="200" label="下单日期" align="center"></el-table-column>
            <el-table-column prop="packedQuantity" align="center">
              <template #header>
                <el-tooltip content="订单关联的提箱单已提箱量" effect="dark" placement="top">
                  <el-button link>
                    已提箱量
                    <el-icon class="el-icon--right">
                      <QuestionFilled />
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="waitPackingQuantity" align="center" width="110">
              <template #header>
                <el-tooltip content="订单关联的提箱单未提箱量" effect="dark" placement="top">
                  <el-button link>
                    未提箱量
                    <el-icon class="el-icon--right">
                      <QuestionFilled />
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
         <div style="display: flex;justify-content: space-between;">
        <el-form-item label="提箱单号">{{ rowData.packingNo }}</el-form-item>
          <el-form-item label="箱型">{{ boxTypeFilter(rowData.boxType) }} </el-form-item>
        <el-form-item label="箱况">
          <template v-if="rowData.boxCondition == 20">
            <el-select  v-model="param.boxCondition" clearable  placeholder="选择箱况" style="width: 200px;">
                <el-option label="适货" value="15"/>
                <el-option label="次新" value="10"/>
            </el-select>
          </template>
          <template v-else>
            <span>{{ boxConditionFilter(rowData.boxCondition) }}</span>
          </template>
        </el-form-item>
        </div>
        <el-form-item label="堆场名称">{{ rowData.yardName }} </el-form-item>
        <el-form-item label="提箱日期" prop="packingDate">
          <el-date-picker v-model="param.packingDate" type="date" :default-value="new Date()" />
        </el-form-item>
        <el-form-item label="箱号" prop="containerNo">
          <template v-if="rowData.containerClassify == 5"> <!--自有箱-->
            <el-input v-model="param.containerNo" clearable @change="inStock"></el-input>
          </template>
          <template v-else> <!--外调箱-->
            <el-input v-model="param.containerNo" clearable></el-input>
          </template>
        </el-form-item>
         <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="param.plateNumber"></el-input>
        </el-form-item>
        <el-form-item :label-width="'25px'">
          <div style=" color:#606266;font-weight:600" class="_asterisk">提箱附件</div>
          <ImgUpload ref="packingRef" v-if="param.drawerPackingRecord" :displayType="2" :fileSize="3" :showNumber="6" :type="'jpg/png/jpeg/pdf/zip'" :limit="10" :drag="true"></ImgUpload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddPackingRecord" style="margin-top: 20px;">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 查看提箱记录 -->
    <el-drawer v-model="param.drawer3" :with-header="false">
      <packingRecord :rowData="rowData" :id="rowData.id"></packingRecord>
    </el-drawer>

    <!-- 提箱单详情 -->
    <el-drawer v-model="param.drawer2" :with-header="false" size="40%"> 
        <span class="_before">提箱单详情</span>
        <el-row class="marginTop20">
          <el-col :span="24">租箱企业：{{ packingInfo.agentName ||'--'}}</el-col>
          <el-col :span="24" class="marginTop5">提箱单号：{{ packingInfo.packingNo ||'--'}}</el-col>
          <el-col :span="24" class="marginTop5">提箱单有效期范围：
            {{ formatDate(packingInfo.packingValidityPeriodStart, 2) }}
            ~
            {{ formatDate(packingInfo.packingValidityPeriodEnd, 2) }}
          </el-col>
          <el-col :span="24" class="marginTop5">类型：{{ param.orderTypeFilter[packingInfo.orderType]||'--' }}</el-col>
          <el-col :span="24" class="marginTop5">箱号：
              <template v-for="(item,index) in packingRecordList[0]?.containerNoList" :key="index">{{item.containerNo}} 
                  <template v-if="index < (packingRecordList[0]?.containerNoList).length - 1">、</template>
              </template>
          </el-col>
        </el-row>
       
        <div class="marginTop15">租箱订单：</div>
        <el-table :data="rentOrderList">
          <el-table-column prop="orderNo" label="订单号" align="center"> </el-table-column>
          <el-table-column label="预计提箱日期" align="center">
            <template #default="scope"> {{ formatDate(scope.row.planPickupDate, 2) }} </template>
          </el-table-column>
          <el-table-column label="下单日期" align="center">
            <template #default="scope"> {{ formatDate(scope.row.createTime, 2) }} </template>
          </el-table-column>
        </el-table>
        <div class="marginTop15">箱型/箱量/箱况：</div>
        <el-table :data="packingRecordList">
          <el-table-column prop="boxType" label="箱型" align="center"> </el-table-column>
          <el-table-column prop="boxQuantity" label="箱量" align="center"> </el-table-column>
          <el-table-column prop="boxCondition" label="箱况" align="center"> </el-table-column>
        </el-table>
        <yardInfoCard :yard="packingInfo"></yardInfoCard>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { downloadIamge } from '@/utils/download'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import ImgUpload from '@/components/upload/uploadFiles-Images'
import { addPackingDetail} from '@/api/orderManage/packingDetail'
import { getTable, getBoxEastTable, getPackingData, addPacking, finishPacking, downloadPacking, orderBoxQty,agentStatusCount} from '@/api/orderManage/packing'
import yardInfoCard from '@/views/components/boxYard/yardInfo.vue'
import { computed, getCurrentInstance, onMounted, onActivated, reactive, ref, watch,nextTick } from 'vue';
import packingRecord from '@/views/components/tiXiangManage/packingRecord.vue';
import {agentSelectPage } from '@/api/boxManage/index';
import { useRoute } from 'vue-router'

import { QuestionFilled,Search,Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils'

const param = reactive({
  //table
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货) 
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  orderTypes: [
    { value: '5', label: '自有', },
    // { value: '10', label: '回调', },
    { value: '15', label: '外调', },
  ],
  orderTypeFilter: { 5: '出租', 10: '回调', 15: '外调' },
  boxCondition:'',
  plateNumber:'',
  drawerPackingRecord:false,
  rentInCurrency:'CNY',
  rentInPrice:0,
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  //  { key: 'total30RentQty', colWidth: '150', title: '30天租量', isTooltip: true, tooltip: "计算近30天的租量，租量数据以当前日期为起点，向前推算30天内完成提箱的集装箱数量;", sortable: true, type: 'text', isCheck: true },
  header: [
    { key: 'businessNo', colWidth: '120', title: '业务编号', type: 'text', isCheck: true },
    { key:'carryCityName', colWidth: '80', title: '提箱城市', type: 'text', isCheck: true },
    { key:'returnCity', colWidth: '150', title: '还箱城市', type: 'moreCity', isCheck: true },
    // { key: 'orderType', colWidth: '100', title: '提箱单类型', type: 'filter', filter: { 5: '出租', 10: '回调', 15: '外调' }, isCheck: true },
    { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '60', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' ,20: '混提'}, isCheck: true },
    { key: 'totalQuantity', colWidth: '80', title: '总箱量', type: 'totalQuantity', isCheck: true },
    { key: 'packedQuantity', colWidth: '80', title: '已提箱量', type: 'totalQuantity', isCheck: true },
    { key: 'totalQuantity',key2: 'packedQuantity', colWidth: '80', title: '未提箱量', type: 'quantity', isCheck: true },
    { key: 'yardName',colWidth: '120', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'status', colWidth: '70', title: '状态', type: 'statusTixiang',  isCheck: true },
    { key: 'packingValidityPeriod', colWidth: '200', title: '提箱单有效期范围', type: 'rangeStatus', isCheck: true },
    { key: 'residuePackingDays', colWidth: '100', title: '剩余提箱天数', isTooltip: true, tooltip: "负数代表超期未提天数", type: 'days',  after: '天',isCheck: true },
    { key: 'packingNo', colWidth: '200', title: '提箱单号', type: '<a>', command: 'showInfo', isCheck: true },
    // { key: 'businessNo', colWidth: '120', title: '业务编号', type: 'text', isCheck: true },
    { key: 'orderList', key2: 'orderNo', colWidth: '200', title: '订单号', type: '/', isCheck: true },
    { key: 'companyName', colWidth: '200',title: '集装箱公司', type: 'text', isCheck: true },
    { key: 'boxEastOperatorUserName', colWidth: '80', title: '联系人', type: 'text', isCheck: true },
    // { key: 'boxEastOperatorUserTel',colWidth: '140', title: '联系电话', type: 'phoneNumber',areaCode:"boxEastOperatorUserAreaCode", isCheck: true },
    // { key: 'status', colWidth: '70', title: '状态', type: 'statusTixiang',  isCheck: true },
    // { key: 'orderList', key2: 'orderNo', colWidth: '100', title: '提箱单附件', type: '/', isCheck: true },
    {
      key: 'operate',
      colWidth: '100',
      title: '提箱单附件',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Document',
          command: 'handleShowContract',
          isShow: (row) => {
            if(JSON.parse(row.packingFileList)!=''){
              return row.packingFileList
            }
          },
        },
      ],
    },
    {
      key: 'operate',
      colWidth: '240',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'Download',
          command: 'downloadFile',
          // content: '下载提箱单',
          name: '下载提箱单',
          isShow: (row: any) => {
            return JSON.parse(row.pdfFile)!='';
          },
        },
        {
          // icon: 'ChatLineSquare',
          command: 'showPackingRecord', //param.drawer3
          // content: '提箱记录',
          name:'提箱记录'
        },
        {
          // icon: 'Plus',
          command: 'goAddPackingRecord', // addPacking
          // content: '添加记录',
          name:'添加记录',
          isShow: (row) => {
            return row.status <= 15;
          },
        },
        {
          // icon: 'Refresh',
          command: 'endPacking',
          // content: '完成',
          name:'提完',
          isShow: (row) => {
            return row.status == 15;
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

// const typeList = computed(() => {
//   const list = [
//     { id: 0, name: '全部' },
//     { id: 5, name: '已发放' },
//     { id: 10, name: '已下载' },
//     { id: 15, name: '提箱中' },
//     { id: 20, name: '已完成' },
//     { id: 25, name: '已作废' },
//     { id: 30, name: '已过期' },
//   ]
//   return list
// })
const typeList = ref([
    { id: 0, name: '全部',num:0},
    { id: 5, name: '已发放',num:0},
    { id: 10, name: '已下载',num:0 },
    { id: 15, name: '提箱中',num:0},
    { id: 20, name: '已完成',num:0},
    { id: 30, name: '已过期',num:0 },
    { id: 25, name: '已作废',num:0},
])

// 还箱单状态: 5-已发放 10-已下载 15-还箱中 20-已完成 25-已过期
// 查询各还箱状态的数量
const getAgentStatusCount = async(data:any) => { 
  await agentStatusCount(data).then((res: any) => {
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //已发放
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10){ //已下载
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //提箱中
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //已完成
              item.num += item1.totalQty
          }else if(item.id == 25 && item1.status == 25){ //已作废
              item.num += item1.totalQty
          }else if(item.id == 30 && item1.status == 30){ //已过期
              item.num += item1.totalQty
          }
        })
      })
    }
  })
}
//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value > new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('提箱日期 须小于等于 今天'))
  }
  return callback()
}
const packingRecordFormRules = {
  cardNo: [
    // { required: true, trigger: "blur", message: "不能为空" },
    { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5!-/:-@[-`{-~\p{S}]{0,10}$/, trigger: "blur", message: "请输入 文字/数字/符号 最长不超过10位" }
  ],
  containerNo: [
    { required: true, trigger: "change", message: "不能为空" },
    // { pattern: /\S+/, trigger: "change", message: "箱号不能包含空格" },
    { pattern: /^[A-Z]{3}U\d{7}$/,trigger: "change",message: "请输入正确格式的箱号(4位大写字母+7位数字)"}
  ],
  packingDate: [{ required: true, trigger: "blur", message: "不能为空" },
  { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
   rentInPrice: [
    { required: true, trigger: "change", message: "不能为空" },
  ],
  imgList: [{ required: true, trigger: "change", message: "提箱附件 不能为空" }]
}
const route = useRoute();
const orderTypeval = ref("")
onActivated(() => {
    if(route.query.refNo){
    searchForm.packingNo=route.query.refNo
  }
    nextTick(() => {
       if(route.name=='JKtiXiangManageHD'){
          orderTypeval.value = "10"
        }else{
          // param.tagName = 'rent'
          orderTypeval.value = "5"
        }
     getTableData()
    })
})

// 验证箱号是否存在库存中
const inStock = (val: any) => {
  val = val?.trim()
  param.containerNo = val
  let boxCondition = ""
  
  if(rowData.value.boxCondition == 20){
    boxCondition = param.boxCondition
  }else{
    boxCondition = rowData.value.boxCondition
  }
  const dataStr = {
    pageNum: 1,
    pageSize: 10000,
    containerNo: val,
    boxType: rowData.value.boxType,
    boxCondition: boxCondition,
    boxEastYardId: rowData.value.yardId,
    statusList: [5] // 5-堆存中、10-提箱中、15-已提、20-未还、25-还箱中 30-未还已卖 35-外加 40-已还箱
  }
  if(!val) return 
  if(rowData.value.companyId){
    let isPrompt = false
    dataStr.companyId = rowData.value.companyId
      agentSelectPage(JSON.stringify(dataStr)).then((res: any) => {
      res.data.list.forEach((item: any) => { 
        if(item.containerNo.length == 11 && item.containerNo == val){
          isPrompt = true
        }else{
          isPrompt = false
        }
      })

      if(!isPrompt){
        param.containerNo = ""
        ElMessage.warning("该箱号不存在集装箱公司堆存中,请重新输入箱号")
      }
    },error => {
      console.log("ERROR:",error)
    })
  }
  
}
function handleTypeChange(val: any) {
  searchForm.status = val
  getTableData()
}

/*货代 查询提箱单分页列表
* @param {String} packingNo 提箱单号
* @param {String} yardName 堆场名称
* @param {String} boxCondition 提箱标准 5-全新   10-次新  15-适货  20-混提 
* @param {String} status 提箱单状态  5-已发放 10-已下载 15-提箱中 20-已完成
*/
let searchForm = reactive({
  pageNum: 1,
  pageSize: 10,
})
function getTableData() {
  // const orderType = param.tagName == 'returnBox' ? 10 : searchForm.orderType
  let data = {
    pageNum: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    packingNo: searchForm.packingNo?.trim(),
    yardName: searchForm.yardName?.trim(),
    boxCondition: searchForm.boxCase,
    businessNo: searchForm.businessNo,
    companyName: searchForm.companyName?.trim(),
    orderType: orderTypeval.value,
    // orderType:"10",
    status: searchForm.status,
    orderNo: searchForm.orderNo?.trim(),
  }
  table.config.loading = true;
  // 获取列表数据
  getAgentStatusCount(data)
  getTable(data).then((res: any) => {
    table.data = res.data.list;
    table.data.forEach((item: any) => {
      item.packingValidityPeriod = formatDate(item.packingValidityPeriodStart, 2) + ' ~ ' + formatDate(item.packingValidityPeriodEnd, 2)
    })
    table.config.total = res.data.total;
  })
  table.config.loading = false;
}
// 重置
function handleReSet() {
  searchForm.packingNo = null
  searchForm.businessNo = null
  searchForm.yardName = null
  searchForm.boxCase = null
  // searchForm.status = null
  searchForm.companyName = null
  // searchForm.orderType = ''
  searchForm.orderNo = null
  getTableData()
}

//分页
function onTablePageChange(page: any) {
  searchForm.pageNum = page.pageNum;
  searchForm.pageSize = page.pageSize;
  getTableData();
};

//箱号组件 emit
const boxInfo = ref({})
const boxInfoData = (id: string, info: any) => {
  if (info) {
    boxInfo.value = info
    param.containerNo = info.containerNo
  }
}

//下载---------------
//packing

const downloadFile = async(rowData: any) => {
  if (rowData.pdfFile) {
    let pdfFile = JSON.parse(rowData.pdfFile)
    pdfFile=pdfFile[0]
    if (!pdfFile.url) return ElMessage.error('未找到文件')
    await downloadIamge(pdfFile.url,pdfFile.originalFileName || new Date(Date.now()+28800000).toISOString())
    await downloadPacking(rowData.id)
    await getTableData()
  } else {
    console.log(rowData)
    ElMessage.error('未找到文件')
  }
}

// 添加提箱记录
const singleTableRef =ref()
const rowData = ref({})
const { proxy } = getCurrentInstance();
const packingRef = ref()
const goAddPackingRecord = async(row: any) => {
  rowData.value = row
  await orderBoxQty(row.id).then((res: any) => {
    res.data.forEach((item: any) => {
      item.waitPackingQuantity = item.totalQuantity - 0 - (item.packedQuantity - 0)
      item.orderTime = formatDate(item.orderTime, 2)
    })
    param.orderList = res.data
    param.drawerPackingRecord = true
    nextTick(() => {
      if(res.data.length==1){
        singleTableRef.value?.toggleRowSelection(res.data[0], true)
        param.orderId = res.data[0].orderId
        param.orderNo =res.data[0].orderNo
      }
    })
     
  }).catch((err: any) => {
    ElMessage.error('查询订单失败！')
  })
}

const handleAddPackingRecord = () => {
  if (!param.orderNo) {
    return ElMessage.warning('请选择提箱订单')
  }
  let boxCondition = ""
  if(rowData.value.boxCondition == 20){
    boxCondition = param.boxCondition
  }else{
    boxCondition = rowData.value.boxCondition
  }
  proxy.$refs.packingRecordFormRef.validate(valid => {
    if (!valid) return
    // const imgList = packingRef.value.resultList || []
    const imgList = packingRef.value.fileList || []
    if (imgList.length == 0) {
      return ElMessage.warning('请上传提箱附件')
    }
    if(!param.orderId) return ElMessage.warning('请选择订单号')
    const data = {
      "orderId": param.orderId,
      "orderNo": param.orderNo,
      "packingId": rowData.value.id,
      // "containerId": boxInfo.value.id,
      // "containerNo": boxInfo.value.containerNo,
      "containerId":"",
      "containerNo": param.containerNo?.trim().toUpperCase(),
      "packingDate": param.packingDate,
      "detailFileList": JSON.stringify(imgList),
      "plateNumber":param.plateNumber,
      "boxCondition": boxCondition || "",
    }
    addPackingDetail(data).then((res: any) => {
      getTableData()
      param.drawerPackingRecord = false
    })
  })
}

//查看提箱记录
const packingRecordList = ref([])
const rentOrderList = ref([])
const showPackingRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
}

//提完
const endPacking = (row: any) => {
  ElMessageBox.confirm('确定已提完？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    finishPacking(row.id).then((res: any) => {
      getTableData();
    })
  }).catch(() => { });
}

//查看提箱单详情
const packingInfo = ref({})
const showInfo = (row: any) => {
  if (!row.id) {
    return ElMessage({ message: '暂无提箱单id信息', type: 'error' })
  }
  param.drawer2 = true;
  getPackingData(row.id).then((res: any) => {
    packingRecordList.value.length = 0
    const data = res.data
    packingInfo.value = res.data
    const packingRecord = {
      boxQuantity: data.totalQuantity, 
      boxType: boxTypeFilter(res.data.boxType), 
      boxCondition: boxConditionFilter(res.data.boxCondition), 
      containerNoList: JSON.parse(data.containerNoList) 
    }
    packingRecordList.value.push(packingRecord)
    rentOrderList.value = JSON.parse(data.orderList)
  })
  showPackingRecord(row) //获取提箱记录list
  param.drawer3 = false //关闭提箱记录抽屉
};


//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '全新' }, { value: 10, label: '次新' }, { value: 15, label: '适货' }, { value: 20, label: '混提' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const packingRecordFormRef=ref()
//
const handleSelectionChange = (val: any) => {
  if (val && val[0]) {
    param.orderId = val[0].orderId
    param.orderNo = val[0].orderNo
  }
}
// 循环下载提箱单附件
const handleShowContract = (row) => {
  ElMessageBox.confirm('确定下载该提箱单附件？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let packingFileList = JSON.parse(row.packingFileList)
    if(packingFileList.length>0){
      packingFileList.forEach((item,index) => {
          if (!item.url) return ElMessage.error('未找到文件')
          downloadIamge(item.url,item.originalFileName || new Date(Date.now()+28800000).toISOString())
      })
    }else{
      return ElMessage.error('未找到文件')
    }
  }).catch(() => { });
}

const resetForm = ()=>{
    param.orderNo=null
    param.orderId=null
  proxy.$refs.packingRecordFormRef?.resetFields()
}
</script>

<style scoped lang="scss">
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
</style>
